<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="发票类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ticketType">
              <j-dict-select-tag type="list" v-model="model.ticketType" dictCode="ticket_type" placeholder="请选择发票类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="发票号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ticketCode">
              <a-input v-model="model.ticketCode" placeholder="请输入发票号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="发票金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ticketMoney">
              <a-input-number v-model="model.ticketMoney" placeholder="请输入发票金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="开票日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ticketDate">
              <j-date placeholder="请选择开票日期" v-model="model.ticketDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fileUrl">
              <j-upload v-model="model.fileUrl"  ></j-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="收票管理子表" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="ticketCollectionManagementDetailTable.loading"
          :columns="ticketCollectionManagementDetailTable.columns"
          :dataSource="ticketCollectionManagementDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

import { getAction, postAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
import {
  getRefPromise,
  VALIDATE_FAILED,
  validateFormModelAndTables
} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'

  export default {
    name: 'TicketCollectionManagementForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          ticketMoney:[{required: true,message:'请输入发票金额'}],
          ticketCode:[{required: true,message:'请输入发票号'}]
        },
        refKeys: ['ticketCollectionManagementDetail', ],
        tableKeys:['ticketCollectionManagementDetail', ],
        activeKey: 'ticketCollectionManagementDetail',
        // 收票管理子表
        ticketCollectionManagementDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '采购订单code',
              key: 'orderCode',
               type: JVXETypes.input,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '收货金额',
              key: 'receiptNum',
               type: JVXETypes.inputNumber,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '已收票金额',
              key: 'receiveTicketNum',
               type: JVXETypes.inputNumber,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '未收票金额',
              key: 'unpaidTicketNum',
               type: JVXETypes.inputNumber,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '订单分配收票金额',
              key: 'allocationNum',
              type: JVXETypes.inputNumber,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                { required: true, message: '请输入订单分配收票金额' },
              ]
            },
            {
              title: '备注',
              key: 'remark',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          add: "/procurement/ticketCollectionManagement/add",
          edit: "/procurement/ticketCollectionManagement/edit",
          queryById: "/procurement/ticketCollectionManagement/queryById",
          ticketCollectionManagementDetail: {
            list: '/procurement/ticketCollectionManagement/queryTicketCollectionManagementDetailByMainId',
            selectByMainId: '/procurement/ticketCollectionManagement/selectByMainId',
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      handleOk() {
        let price=0
        for (let i = 0; i < this.ticketCollectionManagementDetailTable.dataSource.length; i++) {
          price=price+this.ticketCollectionManagementDetailTable.dataSource[i].allocationNum
          if(this.ticketCollectionManagementDetailTable.dataSource[i].allocationNum>this.ticketCollectionManagementDetailTable.dataSource[i].unpaidTicketNum){
            this.$message.error("订单分配收票金额不能大于未收票金额")
            return
          }
        }
        if(price!==this.model.ticketMoney){
          return this.$message.error("订单分配收票金额需要等于发票金额")
        }
        /** 触发表单验证 */
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormModelAndTables(this.$refs.form,this.model, tables)
        }).then(allValues => {
          /** 一次性验证一对一的所有子表 */
          return this.validateSubForm(allValues)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          return this.request(formData)
        }).catch(e => {
          if (e.error === VALIDATE_FAILED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      },
      add(records) {
        if (typeof this.addBefore === 'function') this.addBefore(records)
        // 默认新增空数据
        let rowNum = this.addDefaultRowNum
        if (typeof rowNum !== 'number') {
          rowNum = 1
          console.warn('由于你没有在 data 中定义 addDefaultRowNum 或 addDefaultRowNum 不是数字，所以默认添加一条空数据，如果不想默认添加空数据，请将定义 addDefaultRowNum 为 0')
        }
        this.eachAllTable((item) => {
          //update-begin-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
          setTimeout(()=>{
            item.addRows()
          }, 30)
          //update-end-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
        })
        if (typeof this.addAfter === 'function') this.addAfter(this.model)
        this.edit(this.model)
      },
      addBefore(records){
        records.forEach(record => {
          record.main = record.orderId
        })
        postAction(this.url.ticketCollectionManagementDetail.selectByMainId,records).then((res) => {
          if(res.success){
            console.log("111111111111111111",res.result)
            this.ticketCollectionManagementDetailTable.dataSource.push(...res.result)
          }
        })

      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.ticketCollectionManagementDetail.list, params, this.ticketCollectionManagementDetailTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          ticketCollectionManagementDetailList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },

    }
  }
</script>

<style scoped>
</style>